﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenPasteSpider.usermodel;
using Volo.Abp.Application.Dtos;
using Z.EntityFramework.Plus;

namespace OpenPasteSpider.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [ApiController]
    [Route("/api/spider/user/[action]")]
    public class APIUserController : IBaseController
    {

        private readonly IOpenPasteSpiderDbContext _dbContext;
        private readonly ICacheHelper _cache;
        private readonly ILogger<APIUserController> _logger;
        private readonly ImageHelper _imageHelper;
        private readonly SpiderConfig _config;
        /// <summary>
        /// 初始化
        /// </summary>
        public APIUserController(IOpenPasteSpiderDbContext dbContext,
            ICacheHelper cache,
            ILogger<APIUserController> logger,
            IOptions<SpiderConfig> config,
            ImageHelper imageHelper)
        {
            _dbContext = dbContext;
            _cache = cache;
            _imageHelper = imageHelper;
            _logger = logger;
            _config = config.Value;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult Image(string guid)
        {
            try
            {
                if (String.IsNullOrEmpty(guid))
                {
                    throw new PasteCodeException("验证码代码错误，guid不能为空!");
                }

                //进行特殊符号的替换工作
                if (!new System.Text.RegularExpressions.Regex("[0-9,a-z,A-Z]{16}").Match(guid).Success)
                {
                    throw new PasteCodeException("guid的位数不足，应为16位随机数，不能包含特殊符号，需要为字母和数字的组合");
                }

                if (_cache.Exists(string.Format(PublicString.CacheImageHead, guid))) { throw new PasteCodeException("guid不能重复使用！"); }

                //判断guid是否存在

                string code = _imageHelper.CreateVerifyCode(ImageHelper.VerifyCodeType.NumberVerifyCode);

                _cache.Set(string.Format(PublicString.CacheImageHead, guid), code, 300);

                byte[] codeImage = _imageHelper.CreateByteByImgVerifyCode(code, 80, 36);

                return File(codeImage, @"image/jpeg");
            }
            catch (Exception exl)
            {
                _logger.LogException(exl);
                throw new PasteCodeException(exl.Message);
            }
        }


        /// <summary>
        /// 登录到系统
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<LoginOutputModel> Login(InputLogin input)
        {

            var cachecode = await _cache.GetAsync(string.Format(PublicString.CacheImageHead, input.guid));

            if (String.IsNullOrEmpty(cachecode))
            {
                throw new PasteCodeException("图形验证码超时，请点击刷新！");
            }

            if (cachecode != input.code)
            {
                throw new PasteCodeException("图形验证码错误，请重新输入！");
            }


            var loginlockkey = $"login.try.{input.account}";
            var lockval = await _cache.GetAsync(loginlockkey);
            if (!String.IsNullOrEmpty(lockval))
            {
                if (long.TryParse(lockval, out var timeend))
                {
                    var NowSecond = DateTime.Now.ToUnixTimeSeconds();
                    throw new PasteCodeException($"登录次数过于频繁，请稍后再试！{(timeend - NowSecond)}(s)");
                }
            }

            var user = _dbContext.UserInfo.Where(x => x.Email == input.account).FirstOrDefault();
            //验证账号，添加到缓存中
            if (user != null)
            {
                //var log = new UserLoginLog();
                //log.CreateDate = DateTime.Now;
                //log.LoginIP = ReadClientIP();
                //log.LoginResult = "";
                //log.UserInfo = user;



                if (!user.IsEnable)
                {
                    var longstr = DateTime.Now.AddHours(1).ToUnixTimeSeconds().ToString();
                    await _cache.SetAsync(loginlockkey, longstr.ToString(), 3600);
                    throw new PasteCodeException("账号被禁用，无法继续登录!");
                }

                if (user.PassWord != input.password.ToMd5Lower())
                {
                    //加多少秒时间?
                    SetWaitSecond(input.account, loginlockkey);
                    //log.LoginResult = "密码错误";
                    //_dbContext.Add(log);
                    //await _dbContext.SaveChangesAsync();
                    throw new PasteCodeException("密码错误，请稍后再试!");
                }

                //登录成功，则读取权限列表

                //user.LastLoginTime = DateTime.Now;
                //user.TotalLoginTimes++;
                //await _dbContext.SaveChangesAsync();

                var gradeid = await _dbContext.GradeInfo.Where(x => x.Name == user.Grade).Select(x => x.Id).FirstOrDefaultAsync();

                if (gradeid == 0)
                {
                    throw new PasteCodeException($"账号角色信息有误，无法找到角色:{user.Grade}");
                }
                // utime_uid_grade_token

                //var now = DateTime.Now.ToUnixTimeSeconds();
                var token = user.Id.BuildToken(user.Grade, 10, _config.UserToken);
                //需要免登录多久？
                //var saveString = Newtonsoft.Json.JsonConvert.SerializeObject(bindroles);
                _cache.Set(token, $"{user.Grade}", TimeSpan.FromHours(10));



                return new LoginOutputModel() { RoleString = token, TimeExpire = 36000, Token = token, UserId = user.Id, UserName = user.UserName };

                //var bindroles = await _dbContext.BindUserRole.Where(x => x.UserInfo.Id == user.Id && x.IsEnable).Include(x => x.RoleInfo).AsNoTracking().ToListAsync();
                //if (bindroles != null && bindroles.Count > 0)
                //{
                //    var now = DateTime.Now.ToUnixTimeSeconds();
                //    var token = $"{user.Id}_{now}_{Guid.NewGuid().ToString().Replace("-", "").ToLower()}";
                //    //需要免登录多久？
                //    var saveString = Newtonsoft.Json.JsonConvert.SerializeObject(bindroles);
                //    _cacheClient.Set(token, saveString, TimeSpan.FromHours(10));
                //    //log.LoginResult = "登录成功";
                //    //_dbContext.Add(log);
                //    var tokenlog = new UserTokenLog();
                //    tokenlog.Token = token;
                //    tokenlog.UserId = user.Id;
                //    tokenlog.CreateDate = DateTime.Now;
                //    _dbContext.Add(tokenlog);
                //    await _dbContext.SaveChangesAsync();
                //    return new LoginOutputModel() { RoleString = saveString, TimeExpire = 36000, Token = token, UserId = user.Id, UserName = user.UserName };
                //}
                //else
                //{
                //    //log.LoginResult = "登录成功但未分配权限";
                //    //_dbContext.Add(log);
                //    //await _dbContext.SaveChangesAsync();

                //    throw new PasteException("当前账号未分配权限，请先使用管理账号分配权限后再登录！");
                //}
            }
            else
            {
                SetWaitSecond(input.account, loginlockkey);
                throw new PasteCodeException("当前账号不存在，请先联系管理员添加账号后再试！");
            }
        }



        /// <summary>
        /// 获取登录用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "", "" })]
        public async Task<UserInfoDto> ReadMyInfo()
        {
            var userid = ReadLoginUserId();
            var userinfo = await _dbContext.UserInfo.Where(x => x.Id == userid).AsNoTracking().FirstOrDefaultAsync();

            if (userinfo == null || userinfo == default)
            {
                throw new PasteCodeException("当前用户不存在，请重新登录");
            }

            var dto = ObjectMapper.Map<UserInfo, UserInfoDto>(userinfo);
            //dto.Phone = "";
            dto.Email = "";
            //dto.PassWord = "";

            return dto;
        }

        //更改自己的密码

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //[TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "", "" })]
        //public async Task<ActionBack> ChangePass(string newpass)
        //{
        //    var userid = ReadLoginUserId();
        //    var userinfo = await _dbContext.UserInfo.Where(x => x.Id == userid).AsNoTracking().FirstOrDefaultAsync();

        //    if (userinfo == null || userinfo == default)
        //    {
        //        throw new PasteException("当前用户不存在，请重新登录");
        //    }

        //    if (userinfo.IsEnable)
        //    {

        //        _dbContext.UserInfo.Where(x => x.Id == userid).Update(x => new UserInfo() { PassWord = newpass.ToMd5Lower() });

        //        var daynow = DateTime.Now.AddDays(-1);
        //        var tokens = _dbContext.UserTokenLog.Where(x => x.UserId == userid && x.CreateDate > daynow).ToList();
        //        if (tokens != null && tokens.Count > 0)
        //        {
        //            foreach (var key in tokens)
        //            {
        //                _cacheClient.Delete(key.Token);
        //            }
        //        }

        //        _dbContext.UserTokenLog.Where(x => x.UserId == userid && x.CreateDate > daynow).Delete();
        //    }
        //    else
        //    {
        //        throw new PasteException("账号被禁用，无法更改密码");
        //    }

        //    //移除之前的密钥... .. .

        //    return new ActionBack();
        //}

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "", "" })]
        public async Task<string> ChangePass(InputChangePass input)
        {
            var userid = base.ReadLoginUserId();
            var user = _dbContext.UserInfo.Where(x => x.Id == userid).FirstOrDefault();
            if (user != null && user != default)
            {
                if (!user.IsEnable)
                {
                    throw new PasteCodeException("当前账号被禁用，请联系管理人员！");
                }
                if (input.OldPass.ToMd5Lower() != user.PassWord)
                {
                    throw new PasteCodeException("旧密码错误，请重新输入！");
                }
                user.PassWord = input.NewPlass.ToMd5Lower();
                await _dbContext.SaveChangesAsync();
                return "密码修改成功，请重新登陆！";
            }
            else
            {
                throw new PasteCodeException("当前账号信息有误，无法执行修改密码操作！");
            }
        }

        ///// <summary>
        ///// 返回某一个用户对项目的权限配置
        ///// </summary>
        ///// <param name="userid"></param>
        ///// <returns></returns>
        ///// <exception cref="PasteException"></exception>
        //[HttpGet]
        //[TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
        //public async Task<List<UserAuthModel>> ReadUserAuth(int userid)
        //{
        //    var models = await _dbContext.ModelConfig.Where(x => x.IsEnable).Select(x => new ModelConfigDto
        //    {
        //        Id = x.Id,
        //        Code = x.Code,
        //        Name = x.Name,
        //        IsEnable = false,
        //        Sort = x.Sort
        //    }).ToListAsync();
        //    if (models == null || models.Count == 0)
        //    {
        //        throw new PasteException("请先配置环境信息，没有获取到环境信息列表！");
        //    }

        //    var services = await _dbContext.ServiceInfo.Where(x => x.IsEnable).Include(x => x.Project).Select(x => new ServiceInfoDto
        //    {
        //        Name = x.Name,
        //        Id = x.Id,
        //        Code = x.Code,
        //        Project = new ProjectInfoDto
        //        {
        //            Id = x.Project.Id,
        //            Code = x.Project.Code,
        //            Name = x.Project.Name
        //        }
        //    }).ToListAsync();

        //    var binds = await _dbContext.UserAuth.Where(x => x.UserId == userid).AsNoTracking().ToListAsync();
        //    if (binds == null) { binds = new List<UserAuth>(); }
        //    var datalist = new List<UserAuthModel>();
        //    foreach (var item in services)
        //    {
        //        var bind = binds.Where(x => x.ServiceId == item.Id).FirstOrDefault();
        //        if (bind == null || bind == default)
        //        {
        //            bind = new UserAuth { IsEnable = false, ModelCodes = "" };
        //        }

        //        var modelstrs = bind.ModelCodes.Split(',');

        //        var userauth = new UserAuthModel
        //        {
        //            Id = bind.Id,
        //            IsEnable = bind.IsEnable,
        //            Project = new ProjectInfoDto
        //            {
        //                Id = item.Project.Id,
        //                Name = item.Project.Name,
        //                Code = item.Project.Code
        //            },
        //            Service = new ServiceShortModel
        //            {
        //                Id = item.Id,
        //                Name = item.Name,
        //                Code = item.Code
        //            },
        //            UserId = userid,
        //            Models = new List<ModelConfigDto> { }
        //        };

        //        foreach (var one in models)
        //        {
        //            userauth.Models.Add(new ModelConfigDto
        //            {
        //                Id = one.Id,
        //                Code = one.Code,
        //                Name = one.Name,
        //                IsEnable = (modelstrs.Contains(one.Code))
        //            });
        //        }

        //        datalist.Add(userauth);

        //    }
        //    return datalist;

        //}


        ///// <summary>
        ///// 应该是单个提交的
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
        //public async Task<string> UpdateUserAuth(UserAuthSubmit input)
        //{
        //    // serviceid userid isenable modelcodelist

        //    var find = _dbContext.UserAuth.Where(x => x.UserId == input.userid && x.ServiceId == input.serviceid).FirstOrDefault();
        //    if (find != null && find != default)
        //    {
        //        find.IsEnable = input.isenable;
        //        find.ModelCodes = String.Join(',', input.codes);
        //    }
        //    else
        //    {
        //        _dbContext.Add(new UserAuth
        //        {
        //            UserId = input.userid,
        //            CreateDate = DateTime.Now,
        //            IsEnable = input.isenable,
        //            ModelCodes = String.Join(',', input.codes),
        //            ServiceId = input.serviceid
        //        });
        //    }
        //    await _dbContext.SaveChangesAsync();


        //    return "更新成功！";
        //}

        /// <summary>
        /// 查询推送信息的记录
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <param name="revicerid"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
        public async Task<PagedResultDto<dynamic>> ReadNoticePage(int page = 1, int size = 20, int revicerid = 0)
        {
            var query = _dbContext.NoticeLog.Where(t => 1 == 1).OrderByDescending(xy => xy.Id);
            var user = _dbContext.RevicerInfo.Where(x => 1 == 1).WhereIf(revicerid != 0, x => x.Id == revicerid);
            var pagequery = from log in query
                            join c in user on log.RevicerId equals c.Id into aaa
                            from revicer in aaa.DefaultIfEmpty()
                            select new
                            {
                                CreateDate = log.CreateDate,
                                Id = log.Id,
                                ObjId = log.ObjId,
                                Body = log.Body,
                                Time = log.Time,
                                Name = revicer.Name,
                                Result = log.Success
                            };

            var pagedResultDto = new PagedResultDto<dynamic>();
            pagedResultDto.TotalCount = await query.CountAsync();
            var userList = await query.Page(page, size).ToListAsync();
            var temList = await pagequery.ToListAsync();
            pagedResultDto.Items = temList;
            return pagedResultDto;
        }


        ///// <summary>
        ///// 按照条件查询运行状态数据
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
        //public async Task<dynamic> ReadCharts(InputReportSearch input)
        //{
        //    var readdate = _gettoday(input.datetype);

        //    //Console.WriteLine($"{readdate.datestart}___{readdate.dateend}");

        //    var appname = String.Empty;
        //    if (input.appid != 0)
        //    {
        //        appname = _dbContext.AppInfo.Where(x => x.Id == input.appid).Select(x => x.Name).FirstOrDefault();
        //    }

        //    switch (input.datetype)
        //    {
        //        case "hour":
        //            {
        //                if (input.linuxid != 0)
        //                {
        //                    return await _dbContext.LinuxState.Where(x => x.LinuxId == input.linuxid && x.DataDate >= readdate.datestart && x.DataDate < readdate.dateend).OrderBy(x => x.DataDate).ToListAsync();
        //                }

        //                if (!String.IsNullOrEmpty(appname))
        //                {
        //                    return await _dbContext.DockerState.Where(x =>  x.DataDate >= readdate.datestart && x.DataDate < readdate.dateend && x.DockerName == appname).OrderBy(x => x.DataDate).ToListAsync();
        //                }
        //                else
        //                {
        //                    throw new PasteException("没有查询到其他信息！", CodeLevel.ShowInfo);
        //                }
        //            }
        //        default:
        //            {
        //                if (input.linuxid != 0)
        //                {
        //                    return await _dbContext.LinuxTimeState.Where(x => x.LinuxId == input.linuxid && x.DataDate >= readdate.datestart && x.DataDate < readdate.dateend).OrderBy(x => x.DataDate).ToListAsync();
        //                }

        //                if (!String.IsNullOrEmpty(appname))
        //                {
        //                    return await _dbContext.DockerTimeState.Where(x => x.DataDate >= readdate.datestart && x.DataDate < readdate.dateend && x.DockerName == appname).OrderBy(x => x.DataDate).ToListAsync();
        //                }
        //                else
        //                {
        //                    throw new PasteException("没有查询到其他信息！", CodeLevel.ShowInfo);
        //                }
        //            }
        //    }

        //    //throw new PasteException("没有查询到其他信息！",CodeLevel.ShowInfo);
        //}

        ///// <summary>
        ///// 获取时间日期
        ///// </summary>
        ///// <param name="stype"></param>
        ///// <returns></returns>
        //private (DateTime datestart, DateTime dateend) _gettoday(string stype)
        //{
        //    switch (stype)
        //    {
        //        case "hour"://当前这个小时
        //            {
        //                var _start = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:00:00");

        //                var _end = DateTime.Now.AddHours(1).ToString("yyyy-MM-dd HH:00:00");

        //                return (DateTime.Parse(_start), DateTime.Parse(_end));
        //            }
        //        case "today"://今日
        //            {
        //                var _start = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
        //                var _end = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 00:00:00");
        //                return (DateTime.Parse(_start), DateTime.Parse(_end));
        //            }
        //        case "yesterday"://昨日
        //            {
        //                var _start = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
        //                var _end = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
        //                return (DateTime.Parse(_start), DateTime.Parse(_end));
        //            }
        //        case "week"://本周
        //            {
        //                var daynow = DateTime.Now;
        //                var _start = "";
        //                var _end = "";
        //                var dayweek = daynow.DayOfWeek;
        //                switch (dayweek)
        //                {
        //                    case DayOfWeek.Monday:
        //                        {
        //                            _start = daynow.ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(7).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Tuesday:
        //                        {
        //                            _start = daynow.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(6).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Wednesday:
        //                        {
        //                            _start = daynow.AddDays(-2).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(5).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Thursday:
        //                        {
        //                            _start = daynow.AddDays(-3).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(4).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Friday:
        //                        {
        //                            _start = daynow.AddDays(-4).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(3).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Saturday:
        //                        {
        //                            _start = daynow.AddDays(-5).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(2).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Sunday:
        //                        {
        //                            _start = daynow.AddDays(-6).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(1).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                }
        //                return (DateTime.Parse(_start), DateTime.Parse(_end));

        //            }
        //        case "prevweek"://上周
        //            {
        //                var daynow = DateTime.Now;
        //                var _start = "";
        //                var _end = "";
        //                var dayweek = daynow.DayOfWeek;
        //                switch (dayweek)
        //                {
        //                    case DayOfWeek.Monday:
        //                        {
        //                            _start = daynow.AddDays(-7).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(0).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Tuesday:
        //                        {
        //                            _start = daynow.AddDays(-8).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Wednesday:
        //                        {
        //                            _start = daynow.AddDays(-9).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(-2).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Thursday:
        //                        {
        //                            _start = daynow.AddDays(-10).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(-3).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Friday:
        //                        {
        //                            _start = daynow.AddDays(-11).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(-4).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Saturday:
        //                        {
        //                            _start = daynow.AddDays(-12).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(-5).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                    case DayOfWeek.Sunday:
        //                        {
        //                            _start = daynow.AddDays(-13).ToString("yyyy-MM-dd 00:00:00");
        //                            _end = daynow.AddDays(-6).ToString("yyyy-MM-dd 00:00:00");
        //                        }
        //                        break;
        //                }
        //                return (DateTime.Parse(_start), DateTime.Parse(_end));

        //            }
        //        case "month"://本月
        //            {
        //                var _start = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
        //                var _end = DateTime.Now.AddMonths(1).ToString("yyyy-MM-01 00:00:00");
        //                return (DateTime.Parse(_start), DateTime.Parse(_end));
        //            }
        //        case "prevmonth"://上月
        //            {
        //                var _start = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01 00:00:00");
        //                var _end = DateTime.Now.AddMonths(0).ToString("yyyy-MM-01 00:00:00");
        //                return (DateTime.Parse(_start), DateTime.Parse(_end));
        //            }
        //        default:
        //            break;
        //    }
        //    return (DateTime.Now, DateTime.Now.AddDays(1));
        //}


        /// <summary>
        /// 计算下一次的尝试时间
        /// </summary>
        /// <param name="account"></param>
        /// <param name="lockkey"></param>
        private async void SetWaitSecond(string account, string lockkey)
        {

            var time = 0;
            var loginwaittime = $"login.retry.{account}";
            var retryval = await _cache.GetAsync(loginwaittime);
            if (!String.IsNullOrEmpty(retryval))
            {
                if (int.TryParse(retryval, out time))
                {

                }
            }
            time++;
            await _cache.SetAsync(loginwaittime, time.ToString(), 3600);

            //存储的值
            var nowsecond = DateTime.Now.ToUnixTimeSeconds();
            //添加的时间
            var addsecond = 0;
            switch (time)
            {
                case 1: addsecond = 2; break;
                case 2: addsecond = 2; break;
                case 3: addsecond = 12; break;
                case 4: addsecond = 12; break;
                case 5: addsecond = 22; break;
                case 6: addsecond = 22; break;
                case 7: addsecond = 32; break;
                case 8: addsecond = 32; break;
                case 9: addsecond = 42; break;
                case 10: addsecond = 42; break;
                default: addsecond = 1800; break;
            }

            nowsecond += addsecond;

            await _cache.SetAsync(lockkey, nowsecond.ToString(), addsecond);

        }

    }

    /// <summary>
    /// 更改密码
    /// </summary>
    public class InputChangePass
    {
        /// <summary>
        /// 旧的密码
        /// </summary>
        [Required(ErrorMessage = "旧密码不能为空，请重新输入")]
        public string OldPass { get; set; }

        /// <summary>
        /// 新的密码
        /// </summary>
        [Required(ErrorMessage = "新密码不能为空，请重新输入!")]
        public string NewPlass { get; set; }
    }



}
